//  Date:         	08/08/2018
//  task:         	health analysis
//  project:      	World Development
//  user-written: 	renvars, interflex 

capture log close
clear all
macro drop _all
set more off
version 14.2
set matsize 800 

//  #0:  setup

log using Analysis_health_Anderson,replace text

//  #1: load data
use ubridge_health_long.dta

//  #2: define covariates

foreach cov in c_lpop c_age c_poverty_census c_lugbara_share c_polarization c_HHI_Religion c_literacy c_education c_employed_share c_Nonagriculture_share c_Arua_dist{
	reg treat `cov'
	}

	local controls c.c_age##treat c.c_lugbara_share##treat c.c_literacy##treat c.c_Arua_dist##treat
	su `controls'
	
	local indicators Arua_dist_miss
	tab1 `indicators'

	foreach y in monitoring_index1 effort_index1 input_index1 utilization_index1{
	center `y', replace
	drop `y'
	ren c_`y' `y'
	}
	

//  #3: define outcomes
	
local health_monitoring index_health_monitoring c_V_dho_visit c_V_dho_calls c_V_freq_calls c_V_BE_q67_q62 c_A_insp_qtr c_A_insp_yr
local health_effort index_health_effort c_V_pctpresent c_V_unauthorized_absence c_RegisterBook c_V_outreach
local health_input index_health_input c_V_inv_so_antimalarials c_V_inv_so_ors_analysis c_A_so_antimalarial c_A_so_ors c_A_total_so_rate c_A_Funds_Received 
local health_utilization index_health_utilization c_A_OutPat_Att_Total c_A_total_attendence c_A_OutPat_Ref_Total c_A_OutPat_Diag_Total c_A_TI_Total  c_A_CI_Tot c_A_ANC_IPT c_A_ANC_Iron c_A_ANC_ITN c_A_ANC_Test_Syph c_A_Mat_Admit c_A_Mat_Deliver_InUnit c_A_Mat_Moth_VitA c_A_PN_Att c_A_CH_VitA_Tot c_A_CH_Deworm_Tot
	
replace c_V_unauthorized_absence1=1	
replace c_V_pctpresent1=1 	
	
********************************************************************************
// #4: RUN REGRESSIONS 
********************************************************************************

foreach y in `health_monitoring'  `health_effort'  `health_input' `health_utilization' { 
	capture noisily reg `y'2 treat c.`y'1##treat healthtype
	capture est sto `y'_m1
	
	capture noisily reg `y'2 treat c.`y'1##treat `controls' `indicators' healthtype
	capture est sto `y'_m2

	capture noisily reg `y'3 treat c.`y'1##treat healthtype
	capture est sto `y'_e1
	
	capture noisily reg `y'3 treat c.`y'1##treat `controls' `indicators' healthtype
	capture est sto `y'_e2
	
* drop baseline values of the DV
	capture noisily reg `y'2 treat healthtype
	capture est sto `y'_m3
	
	capture noisily reg `y'2 treat `controls' `indicators' healthtype
	capture est sto `y'_m4

	capture noisily reg `y'3 treat healthtype
	capture est sto `y'_e3
	
	capture noisily reg `y'3 treat `controls' `indicators' healthtype
	capture est sto `y'_e4
	}
	
*************************
// #5: create short-term tbl
*************************
forval c = 1/4  { //*************************************************************
* short term tbl
local one index_health_monitoring_m`c' c_V_dho_visit_m`c' c_V_dho_calls_m`c' c_V_freq_calls_m`c' c_V_BE_q67_q62_m`c' c_A_insp_qtr_m`c'
local two index_health_effort_m`c' c_V_pctpresent_m`c' c_V_unauthorized_absence_m`c' c_RegisterBook_m`c'  c_V_outreach_m`c'	
local three index_health_input_m`c' c_V_inv_so_antimalarials_m`c' c_V_inv_so_ors_analysis_m`c' c_A_Funds_Received_m`c'	
local four index_health_utilization_m`c' c_A_OutPat_Att_Total_m`c' c_A_total_attendence_m`c' c_A_OutPat_Ref_Total_m`c' c_A_OutPat_Diag_Total_m`c' c_A_TI_Total_m`c'  c_A_CI_Tot_m`c' c_A_ANC_IPT_m`c' c_A_ANC_Iron_m`c' c_A_ANC_ITN_m`c' c_A_ANC_Test_Syph_m`c' c_A_Mat_Admit_m`c' c_A_Mat_Deliver_InUnit_m`c' c_A_Mat_Moth_VitA_m`c' c_A_PN_Att_m`c' c_A_CH_VitA_Tot_m`c' c_A_CH_Deworm_Tot_m`c'

	tempfile short
	local n = 0
	foreach i in one two three four {

		suest ``i'' , vce(cluster cluster_id)
	
		preserve

			regsave , pval ci table(e1, parentheses(stderr) format(%8.3fc)) 
			gen grp = `n'
			keep if regexm(var , ":treat_coef") ///
				| regexm(var , ":treat_stderr") ///
				| regexm(var , ":treat_pval") ///
				| regexm(var , ":treat_ci_upper") ///
				| regexm(var , ":treat_ci_lower")
			
			replace var = subinstr(var , "treat_" , "" , .)
			gen stat = substr(var , strpos(var , ":") + 1 , .)
			replace var = substr(var , 1 , strpos(var , "_m`c'_mean") - 1)
			replace var = substr(var , 3 , .) if regexm(var , "^c_")
			
			gen order = _n
			reshape wide e1 order , i(var) j(stat) string
			renvars e1* , prefix(S)
			
			if `n' > 0 {
				append using `short'
				}
			
			save `short' , replace
		
		restore
		local ++n
		}	
******************	
// #6: create long-term tbl
******************

local one index_health_monitoring_e`c' c_V_dho_visit_e`c' c_V_dho_calls_e`c' c_V_freq_calls_e`c' c_V_BE_q67_q62_e`c' c_A_insp_qtr_e`c' 
local two index_health_effort_e`c' c_V_pctpresent_e`c' c_V_unauthorized_absence_e`c' c_RegisterBook_e`c' c_V_outreach_e`c'	
local three index_health_input_e`c' c_V_inv_so_antimalarials_e`c' c_V_inv_so_ors_analysis_e`c' c_A_so_antimalarial_e`c' c_A_so_ors_e`c' c_A_total_so_rate_e`c' c_A_Funds_Received_e`c'	
local four index_health_utilization_e`c' c_A_OutPat_Att_Total_e`c' c_A_total_attendence_e`c' c_A_OutPat_Ref_Total_e`c' c_A_OutPat_Diag_Total_e`c' c_A_TI_Total_e`c'  c_A_CI_Tot_e`c' c_A_ANC_IPT_e`c' c_A_ANC_Iron_e`c' c_A_ANC_ITN_e`c' c_A_ANC_Test_Syph_e`c' c_A_Mat_Admit_e`c' c_A_Mat_Deliver_InUnit_e`c' c_A_Mat_Moth_VitA_e`c' c_A_PN_Att_e`c' c_A_CH_VitA_Tot_e`c' c_A_CH_Deworm_Tot_e`c'


		tempfile long
		local n = 0
		foreach i in one two three {
		
			suest ``i'' , vce(cluster cluster_id)
			
			preserve
		
				regsave , pval ci table(e1, parentheses(stderr) format(%8.3fc)) 
		
				gen grp = `n'
				keep if regexm(var , ":treat_coef") ///
					| regexm(var , ":treat_stderr") ///
					| regexm(var , ":treat_pval") ///
					| regexm(var , ":treat_ci_upper") ///
					| regexm(var , ":treat_ci_lower")
					
				replace var = subinstr(var , "treat_" , "" , .)
				gen stat = substr(var , strpos(var , ":") + 1 , .)
				replace var = substr(var , 1 , strpos(var , "_e`c'_mean") - 1)
				replace var = substr(var , 3 , .) if regexm(var , "^c_")
	
				gen order = _n
				reshape wide e1 order , i(var) j(stat) string
				renvars e1* , prefix(L)

				if `n' > 0 {
					append using `long'
					}
			
				save `long' , replace
			
			restore
			local ++n
			}

	preserve
		use `short' , replace
		merge 1:1 var using `long'
		
		foreach k in S L {
			gen `k'_ci = "[" + `k'e1ci_lower + " , " + `k'e1ci_upper + "]" 
			replace `k'_ci = "" if missing(`k'e1ci_lower)

			destring `k'e1pval , replace
			replace `k'e1pval = `k'e1pval/2 ///
				if real(`k'e1coef) >= 0 & !missing(`k'e1pval)
			replace `k'e1pval = 1-(`k'e1pval/2) ///
				if real(`k'e1coef) < 0
			tostring `k'e1pval , replace format(%12.3f) force
			replace `k'e1pval = "" if `k'e1pval == "."

			}
		drop *lower *upper
		
		tempfile combine`c'
		save `combine`c'' , replace
	restore
	
	preserve	
		use `combine`c'' , clear
		compress

		gsort grp ordercoef -_merge
		include output_replace_edit.do
		drop order* grp _merge
		order var Se1coef Se1stderr S_ci Se1pval  Le1coef Le1stderr L_ci Le1pval 
		saveold health_Anderson`c', replace
	restore
	}

preserve
use health_Anderson1, clear

***************************************
* Table 14 in Supplementary Information
***************************************

list, sep(5)
restore

preserve
use health_Anderson2, clear

***************************************
* Table 15 in Supplementary Information
***************************************

list, sep(5)
restore

estimates clear

*************************************************************
* // #7: modertator
*************************************************************

gen Distance=Arua_dist
gen Wealth = c_poverty_census
graph drop _all

set scheme lean1 // lean schemes is not installed in Stata by default
set more off

*************************************************************
* FIGURE 26 in Supplementary Information
*************************************************************

foreach j in Distance Wealth {
	foreach y in monitoring effort input utilization {
	lab var index_health_`y'2 "Health `y' weighted index"
	lowess index_health_`y'2 `j' 
	interflex index_health_`y'2 treat `j' index_health_`y'1 if Wealth<3 , title("Health `y'") xlabel(`j') dlabel(UBridge) ylabel()  
	return list
	mat list r(estBin)
	mat list r(margeff)
	graph save Health`y'`j', replace
		}
		
	graph combine Healthmonitoring`j'.gph Healtheffort`j'.gph Healthinput`j'.gph Healthutilization`j'.gph
		}	

*************************************************************
* // #8: permutation tests
*************************************************************
set more off

forvalues j=2(1)3{
foreach i in  monitoring effort input utilization {
	regress index_health_`i'`j' treat c.index_health_`i'1##treat healthtype
	mat beta=e(b)
	svmat double beta
	ren beta1 beta`i'`j'
	drop beta2-beta8 
	su beta`i'`j'
	local beta`i'`j' = r(mean)
	ritest treat _b[ treat ], reps(5000) right seed(05042018) saving(`i'`j'A, replace): regress index_health_`i'`j' treat c.index_health_`i'1##treat healthtype

	preserve
			use `i'`j'A, clear
			gen t= `beta`i'`j''
			gen c=0
			replace c=1 if _pm_1 >= t
			egen p = mean(c)
			saveold `i'`j'A, replace
	restore
		}
	}

****************************************		
set more off
set scheme plottig, permanently
preserve 
graph drop _all

* Short-term
foreach i in monitoring effort input utilization {
	use `i'2A.dta, clear
	quietly su t, de
	local t=round(r(mean),.001)
	quietly su p, de
	local p=round(r(mean),.001)
	hist _pm_1 , kdensity lcolor() title(Health `i' (year-1)) addplot(pci 0 `t' 1.75 `t', lc(red) lp(solid) lw(thick)) text(1.25 .4 "pval=`p'",  place(ne) size(small)) text(1.25 `t' "{&tau}=`t'",place(w) size(small)) name(`i'2) xlabel(-.8(.1).8) xsca(r(-.8 .8)) legend(off)
	}
restore 	

* long-term
preserve 

*************************************************************
// FIGURE 4 in Supplementary Information
*************************************************************

foreach i in monitoring effort input utilization{
	use `i'3A.dta, clear
	quietly su t, de
	local t=round(r(p50), .001)
	quietly su p, de
	local p=round(r(p50), .001)
	hist _pm_1 , kdensity lcolor() title(Health `i' (year-2)) addplot(pci 0 `t' 1.75 `t', lc(red) lp(solid) lw(thick)) text(1.25 .4 "pval=`p'",  place(ne) size(small)) text(1.25 `t' "{&tau}=`t'",place(w) size(small)) name(`i'3) xlabel(-.8(.1).8) xsca(r(-.8 .8)) legend(off)
	}

restore 

	graph combine monitoring2 monitoring3 effort2 effort3 input2 input3 utilization2 utilization3, title("Health (weighted indices)") col(2)
	graph export "HealthRIAnderson.pdf", replace
		
log close
clear
exit